import { getRepository } from 'typeorm';
import { NextFunction, Request, Response } from 'express';
import { File } from '../entity/File';
var fs = require('fs');
const fileUploader = require('../service/upload');
export class FileController {
  private clientRepository = getRepository(File);

  async upload(request: Request, response: Response, next: NextFunction) {
    fileUploader(request, response, async (err) => {
      if (err) {
        console.log(err);
        response.json({
          code: '400',
          msg: err,
        });
        return;
      }
      if (request.file) {
        console.log('request.file', request.file);
        let data = fs.readFileSync(request.file.path);
        data = data.toString().replace(/\r\n/g, ',').replace(/\r/g, ',').replace(/\n/g, ',').replace(/,{2,}/g, ',');
        let file = new File();
        file.original_name = request.file.originalname;
        file.url = 'upload-location/' + request.file.filename;
        file.extend = request.file.originalname.slice(request.file.originalname.lastIndexOf('.'));
        await this.clientRepository.save(file);
        request.file.absolute_path = 'static/' + request.file.filename;
        response.json({
          code: '200',
          status: 'done',
          msg: '上传成功',
          result: request.file,
          fileName: request.file.originalname.slice(0, request.file.originalname.lastIndexOf('.')),
          data: data,
        });
      } else {
        response.json({
          status: 'error',
          code: '500',
          msg: err,
        });
      }
    });
  }
}
